package com.sykj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sykj.bean.bis.BisBagRecord;
import com.sykj.bean.bis.BisBusinessOrder;
import com.sykj.bean.bis.BisNurseBag;
import com.sykj.bean.bis.BisNurseProject;
import com.sykj.config.aop.DuplicateSubmit;
import com.sykj.service.BisBagRecordService;
import com.sykj.service.BisBusinessOrderService;
import com.sykj.service.BisNurseBagService;
import com.sykj.service.BisNurseProjectService;
import com.sykj.util.IDUtils;
import com.sykj.util.reponse.CommonEnum;
import com.sykj.util.reponse.ResultBody;
import com.sykj.util.websocket.WebSocket;
import com.sykj.util.wepay.PayCommonUtil;
import com.sykj.util.wepay.PayConfigUtil;
import com.sykj.util.wepay.XMLUtil;
import com.sykj.util.wepay.ZxingUtil;
import com.sykj.util.wepay.websocket.CreateImg;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: BeautyClub
 * @description: 微信扫码支付
 * @author: qiaoli
 * @create: 2020-08-11 10:34
 */
@RestController
@RequestMapping("/wepay")
public class WePayController {
    @Autowired
    BisNurseBagService bisNurseBagService;

    @Autowired
    BisBusinessOrderService bisBusinessOrderService;

     @Autowired
    BisBagRecordService bisBagRecordService;

    @Autowired
    BisNurseProjectService bisNurseProjectService;

    /**
     * 功能描述:  生成微信支付二维码
     * @Param:
     * @Return:
     * @Author: Feiwo Sicun
     * @Date: 2020/8/11 14:49
     */
    @ResponseBody
    @RequestMapping("/returnImg/{name}/{orderId}/{bagId}")
    public ResultBody testImages(@PathVariable("name") String name, @PathVariable("orderId")String orderId,@PathVariable("bagId")String bagId, HttpServletResponse response) throws Exception {

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.gt("remain_num",0);
        queryWrapper.eq("bag_id",bagId);
        BisNurseBag one = bisNurseBagService.getOne(queryWrapper);
                if(one==null){
                      return  new ResultBody(CommonEnum.WaPay_IMG_ERROR);
                             }


        String result = PayCommonUtil.weixin_pay("1", name, orderId);//获取微信返回的二维码对应的字符串
        String zhuan = CreateImg.zhuan(result);
        zhuan= "data:image/jpg;base64," + zhuan;
        return  new ResultBody(CommonEnum.WaPay_IMG_SUCCESS,zhuan);
    }

/**
 * 功能描述:  微信支付成功回调
 * @Param: [request, response]
 * @Return: void
 * @Author: Feiwo Sicun
 * @Date: 2020/8/11 14:48
 */
@RequestMapping("/weixin_notify")
public void weixin_notify(HttpServletRequest request, HttpServletResponse response) throws Exception {

    InputStream inputStream;
    StringBuffer sb = new StringBuffer();
    inputStream = request.getInputStream();
    String s;
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    while ((s = in.readLine()) != null) {
        sb.append(s);
    }
    in.close();
    inputStream.close();

    //解析xml成map
    Map<String, String> m = new HashMap<String, String>();
    m = XMLUtil.doXMLParse(sb.toString());

    //过滤空 设置 TreeMap
    SortedMap<Object, Object> packageParams = new TreeMap<>();
    Iterator it = m.keySet().iterator();
    while (it.hasNext()) {
        String parameter = (String) it.next();
        String parameterValue = m.get(parameter);

        String v = "";
        if (null != parameterValue) {
            v = parameterValue.trim();
        }
        packageParams.put(parameter, v);
    }

    // 账号信息
    String key = PayConfigUtil.API_KEY; // key

    System.err.println(packageParams);
    String out_trade_no = (String) packageParams.get("out_trade_no");//订单号,实际开发中应该在下面的 IF 中,除非需要对每个订单的每次支付结果做记录
    //判断签名是否正确
    if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
        //------------------------------
        //处理业务开始
        //------------------------------
        String resXml = "";
        if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
            // 这里是支付成功
            //////////执行自己的业务逻辑////////////////
            String mch_id = (String) packageParams.get("mch_id");
            String openid = (String) packageParams.get("openid");
            String is_subscribe = (String) packageParams.get("is_subscribe");
            // String out_trade_no = (String)packageParams.get("out_trade_no");

            String total_fee = (String) packageParams.get("total_fee");

            System.err.println("mch_id:" + mch_id);
            System.err.println("openid:" + openid);
            System.err.println("is_subscribe:" + is_subscribe);
            System.err.println("out_trade_no:" + out_trade_no);
            System.err.println("total_fee:" + total_fee);

            //////////执行自己的业务逻辑////////////////
            Session session = WebSocket.getAllClients().get(out_trade_no);
            session.getAsyncRemote().sendText("ok");


            System.err.println("支付成功");

            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            //知道支付成功了,应该通知页面支持成功,让页面执行跳转动作
            //需要 websocket
            //找到这个订单对应的页面的 websocket, 然后发送数据给页面即可
              /*  Session session = WebSocket.getAllClients().get(out_trade_no);//当前订单对应的页面的 websocket 连接

                if (session != null) {
                    session.getAsyncRemote().sendText("支付成功");//实际开发中请发送正式数据 比如 json 等等
                }*/

        } else {

            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        //------------------------------
        //处理业务完毕
        //------------------------------
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    } else {
        System.err.println("通知签名验证失败");
    }

}
//
    /**
     * 功能描述: 支付成功后 开始将其关联信息填充至数据库
     * 购买礼包
     * @Param: [bagId, orderId, customUserId]
     * @Return: com.sykj.util.reponse.ResultBody
     * @Author: Feiwo Sicun
     * @Date: 2020/8/11 14:48
     */
//    @DuplicateSubmit
  @RequestMapping("/savadate/{bagId}/{orderId}/{customUserId}")
  @Transactional
    public ResultBody     Savadate(@PathVariable("bagId")String bagId,@PathVariable("orderId")String orderId,@PathVariable("customUserId")String customUserId){
      BisNurseBag byId = bisNurseBagService.getById(bagId);
      //  让其库存减去一
      UpdateWrapper updateWrapper=new UpdateWrapper();
      updateWrapper.eq("bag_id",bagId);
      updateWrapper.set("remain_num",byId.getRemainNum()-1);
      boolean update = bisNurseBagService.update(updateWrapper);


      //  添加 营业订单表
      BisBusinessOrder bisBusinessOrder =new BisBusinessOrder();
      bisBusinessOrder.setOrderId(orderId);
      bisBusinessOrder.setOrderContent("购买礼包");
      bisBusinessOrder.setProjectId(bagId);
      bisBusinessOrder.setCustomUserId(customUserId);
      bisBusinessOrder.setOrderType("2");
//      bisBusinessOrder.setOrderMoney(byId.getBagTotalPrice());
      bisBusinessOrder.setPayMoney(0.01);
      bisBusinessOrder.setPayWay("1");
      bisBusinessOrder.setBuyNum(1);
      Timestamp timeStamp = new Timestamp(new Date().getTime());
      bisBusinessOrder.setPayTime(timeStamp);
      bisBusinessOrder.setOrderStatus("3");
      bisBusinessOrder.setCreateTime(timeStamp);
      bisBusinessOrder.setOrderSource("1");
      BisNurseBag b=  bisNurseBagService.getById(bagId);
      // 添加订单金额
      bisBusinessOrder.setOrderMoney(b.getBagTotalPrice());
      // 默认商家id
      bisBusinessOrder.setShopId("778516368");
      boolean save = bisBusinessOrderService.save(bisBusinessOrder);
      // 添加 购买礼包记录
      BisBagRecord bisBagRecord=new BisBagRecord();

      bisBagRecord.setRecordId(IDUtils.createID());
      bisBagRecord.setBagId(bagId);
      bisBagRecord.setValidDay(byId.getOverdueTime());
      bisBagRecord.setCustomUserId(customUserId);
      bisBagRecord.setBuyNum(1);
      bisBagRecord.setOrderId(orderId);
      bisBagRecord.setShareUserId(customUserId);
      bisBagRecord.setStatus("1");
      bisBagRecord.setReceiveStatus("1");

      boolean save1 = bisBagRecordService.save(bisBagRecord);

      if(save==true && save1 ==true && update==true){
          return  new ResultBody(CommonEnum.SUCCESS);
      }else{
          return new ResultBody(CommonEnum.WaPay_SAVA_ERROR);
      }

    }

    /**
     * 功能描述: 购买单个项目 并预约此项目
     * @Param: [shopId, projectId, customUserId, orderId]
     * @Return: com.sykj.util.reponse.ResultBody
     * @Author: Feiwo Sicun
     * @Date: 2020/8/12 14:21
     */
//    @DuplicateSubmit
    @Transactional
   @RequestMapping("/buyproject/{shopId}/{projectId}/{customUserId}/{orderId}/{date}")
    public ResultBody   BuyProject(@PathVariable("shopId")String shopId,@PathVariable("projectId")String projectId,@PathVariable("customUserId")String customUserId,@PathVariable("orderId")String orderId,@PathVariable("date")String date){
       Timestamp timeStamp = new Timestamp(new Date().getTime());
       //  添加 营业订单表
       BisBusinessOrder bisBusinessOrder =new BisBusinessOrder();

       bisBusinessOrder.setOrderId(orderId);

       bisBusinessOrder.setShopId(shopId);
       bisBusinessOrder.setOrderContent("预约购买项目");

       bisBusinessOrder.setProjectId(projectId);
        // 预约时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Timestamp timeStamp1 = new Timestamp(dateTime.getTime());
        bisBusinessOrder.setSubscribeTime(timeStamp1);


//       bisBusinessOrder.setSubscribeTime(timeStamp);
       bisBusinessOrder.setCustomUserId(customUserId);
       bisBusinessOrder.setOrderType("3");
        BisNurseProject byId = bisNurseProjectService.getById(projectId);
        // 将订单金额添加至订单表中
        bisBusinessOrder.setOrderMoney(byId.getActivePrice());
       bisBusinessOrder.setPayMoney(0.01);
       bisBusinessOrder.setPayWay("1");
       bisBusinessOrder.setBuyNum(1);
       bisBusinessOrder.setPayTime(timeStamp);
       // 预约此项目
       bisBusinessOrder.setOrderStatus("0");
       bisBusinessOrder.setCreateTime(timeStamp);
       bisBusinessOrder.setOrderSource("1");
       // 添加服务员工
        bisBusinessOrder.setServerUserId("1595638059502");
        // 操作员工
        bisBusinessOrder.setHandleUserId("1595638059502");
       boolean save = bisBusinessOrderService.save(bisBusinessOrder);

       if(save==true){
           return  new ResultBody(CommonEnum.BOOKED_PROJECT_SUCCESS);
       }else{
           return new ResultBody(CommonEnum.BOOKED_PROJECT_ERROR);
       }


    }



    /**
     * 功能描述:  生成微信支付二维码
     * @Param:
     * @Return:
     * @Author: Feiwo Sicun
     * @Date: 2020/8/11 14:49
     */
    @ResponseBody
    @RequestMapping("/projectimg/{name}/{orderId}/{projectId}")
    public ResultBody ProjectImg(@PathVariable("name") String name, @PathVariable("orderId")String orderId,@PathVariable("projectId")String projectId, HttpServletResponse response) throws Exception {

        BisNurseProject byId = bisNurseProjectService.getById(projectId);
        if(byId==null){
            return  new ResultBody(CommonEnum.WaPay_IMG_ERROR);
        }


        String result = PayCommonUtil.weixin_pay("1", name, orderId);//获取微信返回的二维码对应的字符串
        String zhuan = CreateImg.zhuan(result);
        zhuan= "data:image/jpg;base64," + zhuan;
        return  new ResultBody(CommonEnum.WaPay_IMG_SUCCESS,zhuan);
    }

}
